import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/pick/ai_model_logic.dart';
import 'package:sports_new/entity/ai/ai_item_entity.dart';
import 'package:sports_new/entity/ai/ai_pay_entity.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../utils/routes.dart';
import '../../../utils/user.dart';
import '../../../utils/utils.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../ai/ai_type.dart';

List<Widget> bottomLabel(
    {required String adviseName, required String? advise, String? odds}) {
  return [
    QkdText("$adviseName：${advise ?? "无"}"),
    Container(width: 10),
    if (odds != null && odds != "") QkdText(odds)
  ];
}

class AiMatchItem extends StatelessWidget {
  final CardStyle? cardStyle;
  final AiType? type;
  final AiItemEntity item;
  final String? ticketName;
  final EdgeInsets? margin;
  final ValueChanged<bool>? onChange;
  final Function()? onTap;

  AiMatchItem(
      {super.key,
        this.cardStyle,
        required this.item,
        required this.type,
        this.onChange,
        this.margin,
        this.onTap,
        this.ticketName
      });

  late final AiModelLogic logic = Get.find<AiModelLogic>(tag: type?.tag);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Block(
          cardStyle: cardStyle ??
            CardStyle(
              margin: margin ?? const EdgeInsets.only(bottom: 8),
              padding: const EdgeInsets.fromLTRB(12, 12, 0, 0)),
          child: Column(
            children: [
              top(),
              Container(height: 10),
              middle(),
              Container(height: 8),
              const Divider(height: 0.5,color: Colours.greyEE).paddingSymmetric(horizontal: 12),
              bottom()
            ],
          )),
        if (item.aiResult != null && item.aiResult != "") ...[
          Positioned(
              top: 0,
              right: 0,
              child: Image.asset(height: 20, Utils.getImgPath("ai_tag.png"))),
          Positioned(
            top: 0,
            right: 0,
            child: Container(
              width: 73,
              height: 18,
              alignment: Alignment.center,
              child: QkdText(item.aiResult ?? "",
                fontSize: 12, color: Colours.white
              ),
            ),
          )
        ]
      ],
    );
  }

  Widget top(){
    return DefaultTextStyle(
      style: const TextStyle(color: Colours.grey66, fontSize: 11),
      child: GestureDetector(
        onTap: () => Get.toNamed(Routes.leagueDetail,arguments: "${item.leagueId}"),
        child: Row(
          children: [
            QkdText(item.leagueName ?? "",needCenter: true),
            Container(width: 6),
            QkdText(
              DateTime.tryParse(item.matchTime ?? "")
                  ?.formatedString("MM-dd HH:mm"),
              height: 1.2,
            ),
            Container(width: 6),
            QkdText(ticketName ?? (item.matchNo ?? ""))
          ],
        ),
      ),
    );
  }

  Widget middle(){
    return Row(
      children: [
        Expanded(
          flex: 12,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              team(
                item.homeLogo,
                item.homeName,
                item.homeRanking,
                item.homeScore90
              ),
              Container(height: 6),
              team(
                item.guestLogo,
                item.guestName,
                item.guestRanking,
                item.guestScore90
              )
            ]
          ).tap(() => Get.toNamed(Routes.zqMatchDetail,
              arguments: item.matchId)),
        ),
        Expanded(flex: 7, child: rightArea())
      ],
    );
  }

  Widget bottom(){
    return  DefaultTextStyle(
      style: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w500,
          color: Colours.main),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 6),
        child: item.isOpen != 1?
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(width: 16,Utils.getImgPath("ai_lock.png")),
            Container(width: 4),
            QkdText(
              item.priceId.hasValue?
              "${item.price?.changeUnit.trim()}解锁":"立即开通",
              color: Colours.main
            ),
          ],
        ).tap(() async{
          onTap?.call();
          await User.needLogin(() async {
            if(item.priceId.hasValue){
              await logic.toPay(
                AiPrice(
                    id: item.priceId,
                    price: item.price == "会员免费"?"0":item.price,
                    aiId: item.aiMatchId
                )
              );
            }else {
              Get.toNamed(
                  Routes.aiPay,arguments: type?.tag
              )?.then((value) => onChange?.call(true));
            }
          });
        }):
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            if(type != AiType.bounce){
              onTap?.call();
              Get.toNamed(
                  Routes.aiDetail,
                  arguments: type,
                  parameters: {"id":item.matchId.toString()}
              );
            }
          },
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if(type == AiType.bounce)
                QkdText(item.content ?? ""),
              Row(
                children: <Widget>[
                  const Spacer(),
                  if(type != AiType.bounce && type != AiType.combo)...[
                    const QkdText("详情",
                      height: 1.2,fontSize: 12,color: Colours.grey99
                    ),
                    Container(width: 2),
                    Image.asset(width: 12,Utils.getImgPath("arrow_right_36.png")),
                  ],
                  Container(width: 12)
                ].insertWith(0, options()),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget team(String? logo, String? name, String? rank, int? score) {
    return Row(
      children: [
        Expanded(
          child: LayoutBuilder(builder: (context, cons) {
            return Row(
              children: [
                CachedNetworkImage(
                    width: 28,
                    height: 28,
                    placeholder: (context, url) => Styles.placeholderIcon(),
                    errorWidget: (context, url, error,) =>
                      Image.asset(Utils.getImgPath("zq_placeholder.png")),
                    imageUrl: logo ?? ""),
                Container(width: 8),
                Container(
                  constraints: BoxConstraints(maxWidth: cons.maxWidth - 58),
                  child: QkdText(name ?? "", fontWeight: FontWeight.w500),
                ),
                Container(width: 2),
                if (rank.hasValue)
                  QkdText("[$rank]",fontSize: 11, color: Colours.grey99)
              ],
            );
          }),
        ),
        Container(
          margin: const EdgeInsets.only(right: 35),
          alignment: Alignment.center,
          child: QkdText(score != null ? "$score" : "",
            fontWeight: FontWeight.w500,color: Colours.grey66
          ),
        )
      ],
    );
  }

  Widget rightArea() {
    switch (type) {
      case AiType.faith:
        return Container(
          padding: const EdgeInsets.only(right: 8),
          alignment: Alignment.centerRight,
          child: Image.asset(width: 48, Utils.getImgPath("faith_icon.png")),
        );
      case AiType.assess:case AiType.radar:
        return Column(
          children: [
            if(item.aiIndex.hasValue)
            QkdText(item.aiIndex,
              fontSize: 28,
              color: Colours.main,
              fontFamily: "YouShe",
              needCenter: true
            ),
            if(item.level.hasValue)
            RatingBar(
              initialRating: (item.level?? 0)/(type == AiType.assess?1:2),
              allowHalfRating: true,
              itemCount: 5,
              itemSize: 16,
              ignoreGestures: true,
              unratedColor: Colours.grey99,
              ratingWidget: RatingWidget(
                full: Image.asset(
                  width: 16,
                  color: Colours.main,
                  Utils.getImgPath("match_info_star_on.png")
                ),
                half: Image.asset(
                    width: 16,
                    Utils.getImgPath("match_info_star_half.png")
                ),
                empty: Image.asset(
                  width: 16,
                  Utils.getImgPath("match_info_star_off.png")
                )
              ),
              onRatingUpdate: (rating) => 0
            ),
          ],
        ).alignEnd.paddingOnly(right: 12);
      case AiType.pre:
        List<String> list = ["升盘", "降盘", "降水"];
        return item.aiIndex.noValue == true?Container()
          :Container(
            padding: const EdgeInsets.only(right: 36),
            alignment: Alignment.centerRight,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Column(
                  children: [
                    Image.asset(
                      width: 20,height: 20,
                      Utils.getImgPath("ai_pre_${item.aiIndex}.png")),
                    Container(height: 7),
                    QkdText(
                      list[item.aiIndex.toInt()! - 1],
                      color: Colours.grey99
                    )
                  ],
                ),
              ],
            ),
          );
      default:
        return Column(
          children: [
            QkdText(item.aiIndex ?? "",
              fontSize: 29.12,
              color: item.aiIndex != null ? Colours.main : Colours.white,
              fontFamily: "YouShe"
            ),
            QkdText("${item.aiIndexName}",
              color: item.aiIndex != null ? Colours.grey99 : Colours.white
            )
          ]
        );
    }
  }

  List<Widget> options() {
    List<String> names = [];
    List<List<int>> options = [];
    if (item.aiOption?.hasValue == true) {
      for (var i = 0; i < item.aiOption!.length; i++) {
        names.add(item.aiOption?[i].name?.hasValue == true?"${item.aiOption?[i].name ?? " "}:":"");
        options.add([i]);
      }
    }
    return List.generate(
        names.length,
          (index) => Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              QkdText(names[index], color: Colours.grey99),
              Container(width: 6),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: List.generate(options[index].length, (i) {
                  var entity = item.aiOption?[options[index][i]];
                  return Row(children: [
                    QkdText(entity?.option ?? "",color: entity?.hit == true?Colours.main:Colours.grey99),
                    Container(width: 10),
                    if (entity?.odds != null) QkdText(entity?.odds ?? "",color: entity?.hit == true?Colours.main:Colours.grey99)
                  ]);
                }))
          ]
        ));
  }
}
